package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class SubjectThreeResultController {
	// 自动注入
	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private CustomLogService customLogService;
	
	@Autowired
	private SubjectThreeResultService subjectThreeResultService;
	
	@Autowired
	private SubjectThreeResultentryService subjectThreeResultentryService;
	
	@Autowired
	private SubjectThreeRegService subjectThreeRegService;
	
	@Autowired
	private SubjectThreeRegentryService subjectThreeRegentryService;

	//自定义流程工具
	private Axamine axamine = new Axamine();

	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();
	/**
	 * 查找科目三考试结果信息
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/querySubjectThreeResult/look.action")
	public String selSubjectThreeResult(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "fdescription", defaultValue = "") String fdescription
            , @RequestParam(value = "cfstudentname", defaultValue = "") String cfstudentname
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "")String endTime
			, @RequestParam(value = "type",defaultValue = "") String type
			, @RequestParam(value = "selectState",required = false,defaultValue = "-1") String selectState
			, @RequestParam(value = "cfexmaresult",defaultValue = "")String cfexmaresult)throws Exception{
		PageBean<SubjectThreeResult> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            fdescription = fdescription.trim();
            cfstudentname = cfstudentname.trim();
            beginTime=beginTime.trim();
            endTime=endTime.trim();
			if("1".equals(selectState)){//如果传过来的标记为1 所以业务日期为空默认查询全部
				pb=getPageBean(request,user.getFcompanyid(),fnumber,fdescription,cfstudentname,null,null,cfexmaresult);
			}else{
				//默认时间
				if ("".equals(beginTime) && "".equals(endTime)) {
					beginTime = TimeFormat.getMonth();
					endTime = TimeFormat.getNowTime();
				}
				//获取分页
				pb=getPageBean(request,user.getFcompanyid(),fnumber,fdescription,cfstudentname,beginTime,endTime,cfexmaresult);
			}

            //获取当前分页的值
            List<SubjectThreeResult> subjectThreeResultList = pb.getBeanList();
			//把获取到的数据传回页面
			if(cfstudentname.equals("")){
				cfstudentname=null;
			}
			if ("".equals(cfexmaresult)||"0".equals(cfexmaresult)){
				cfexmaresult=null;
			}

			for (SubjectThreeResult subjectThreeResult : subjectThreeResultList) {
				//获取子类信息
				List<SubjectThreeResultentry> subjectThreeResultentries = subjectThreeResultentryService.selSubjectThreeResultentryByParentId(subjectThreeResult.getFid(),cfstudentname,cfexmaresult);
				//放入集合
				subjectThreeResult.setSubjectThreeResultentryList(subjectThreeResultentries);
			    if (subjectThreeResultentries==null&&"".equals(subjectThreeResultentries)&&cfexmaresult!=null){
					iteratorRemove(subjectThreeResultList,subjectThreeResult);
				}
			}//生成信息总数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//返回界面的搜索条件
			request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fdescription", fdescription);
            request.setAttribute("cfstudentname", cfstudentname);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);
            request.setAttribute("subjectThreeResultList", subjectThreeResultList);
            request.setAttribute("pb", pb);
            request.setAttribute("type",type);
			request.setAttribute("selectState",selectState);
			request.setAttribute("cfexmaresult",cfexmaresult);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
		return"backHome/examManage/subjectThreeResult/subjectThreeResultList";
	}

	/**
	 * 科目二考试登记字段筛选
	 * @param p
	 * @param request
	 * @return
	 */
	@RequestMapping("/subjectThreeList")
	@ResponseBody
	public Object subjectThreeList(@RequestBody(required=true) Map<String,Object> p, HttpServletRequest request){
		ArrayList<String> arr= (ArrayList<String>) p.get("outList");
		request.getSession().setAttribute("subjectThreeList",arr);
		return arr;
	}




	/**
	 * 跳转到增加科目三考试结果登记页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoAddSubjectThreeResult")
	public String intoAddSubjectThreeResult(HttpServletRequest request,String type)throws Exception{
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    //获取组织
	    Department department = departmentService.queryAdminByFid(user.getFcompanyid());
	    /*获取当前时间*/
        String createTime = TimeFormat.timeFormat(new Date());
	    //获取上一个编码
        /*String number = subjectThreeResultService.selectFnumber(user.getFcompanyid());*/
        //获取编码
        String fnumber = GetFnumber.fnumbers("SF");
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//业务时间
		String time = sdf.format(new Date());
        request.setAttribute("user", user);
        request.setAttribute("createTime", createTime);
	    request.setAttribute("department", department);
	    request.setAttribute("fnumber", fnumber);
	    request.setAttribute("type",type);
	    request.setAttribute("time",time);
		return "backHome/examManage/subjectThreeResult/addSubjectThreeResult";
	}
	/**
	 * 增加科目三考试结果登记
	 * @param request
	 * @param subjectThreeResult
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addSubjectThreeResult")
	public String addSubjectThreeResult(HttpServletRequest request,SubjectThreeResult subjectThreeResult)throws Exception{
		String [] stuid=request.getParameterValues("stuid");
		String [] stufseq=request.getParameterValues("stufseq");
		String [] stucfzkzmbh=request.getParameterValues("stucfzkzmbh");
		String [] stufnumber=request.getParameterValues("stufnumber");
		String [] stuname=request.getParameterValues("stuname");
		String [] stucfidcardno=request.getParameterValues("stucfidcardno");
		String [] stucfsex=request.getParameterValues("stucfsex");
		for (int i = 0; i < stucfsex.length; i++) {
			if(stucfsex[i].equals("男")){
				stucfsex[i]="1";
			}else{
				stucfsex[i]="2";
			}
		}
		String [] stucfsjhm=request.getParameterValues("stucfsjhm");
		String [] stucflxdh=request.getParameterValues("stucflxdh");
		String [] stucfslzjcxdh=request.getParameterValues("stucfslzjcxdh");
		String [] stucfclazzName=request.getParameterValues("stucfclazzName");
		String [] stucfamount=request.getParameterValues("stucfamount");
		String [] stucfreceived=request.getParameterValues("stucfreceived");
		String [] stucfarrearage=request.getParameterValues("stucfarrearage");
		String [] stucffavorable=request.getParameterValues("stucffavorable");
		String [] stucfvip=request.getParameterValues("stucfvip");
		String [] stucflocal=request.getParameterValues("stucflocal");
		for (int i = 0; i < stucflocal.length; i++) {
			if(stucflocal[i].equals("本地")){
				stucflocal[i]="1";
			}else if(stucflocal[i].equals("外地")){
				stucflocal[i]="2";
			}else{
				stucflocal[i]="3";
			}
		}
		String [] stucfexamresult=request.getParameterValues("stucfexamresult");
		String [] stucfremark=request.getParameterValues("stucfremark");
		/*获取uuid*/
        String uuid = GetFid.UUIDIntoFid();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        subjectThreeResult.setFid(uuid);
        //公司id
        subjectThreeResult.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        subjectThreeResult.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        subjectThreeResult.setFcreatetime(createTime);       
        //创建人id
        subjectThreeResult.setFcreatorid(user.getFid());
        //增加
        int row =subjectThreeResultService.addSubjectThreeResult(user,subjectThreeResult, stuid, stufseq, stucfzkzmbh, stufnumber, stuname, stucfidcardno,
        		stucfsex, stucfsjhm, stucflxdh, stucfslzjcxdh, stucfclazzName, stucfamount, stucfreceived, stucfarrearage, stucffavorable, 
        		stucfvip, stucflocal, stucfexamresult, stucfremark);
        String result="";
        if(row >0){
			result ="1";
		}
        //添加日志
        customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目三考试结果登记进行增加", null, user.getFid());
		return "redirect:/DrivingSys/intoAddSubjectThreeResult?type="+result;
	}
	
	/**
	 * 跳转到修改科目三考试结果登记页面
	 * @param request
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoUpdateSubjectThreeResult")
	public String intoUpdateSubjectResult(HttpServletRequest request,
			@RequestParam(value="fid",required=false) String fid)throws Exception{
		//获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //获取组织
	    Department department = departmentService.queryAdminByFid(user.getFcompanyid());
	    //获取父类信息
	    SubjectThreeResult subjectThreeResult=subjectThreeResultService.selectSubjectThreeResultByFid(fid);
	    if(subjectThreeResult == null){
			return "/error/not_data";//单据不存在则跳转到错误页面
		}
	    //查找子类信息
	    subjectThreeResult.setSubjectThreeResultentryList(subjectThreeResultentryService.selSubjectThreeResultentryByParentId(subjectThreeResult.getFid(), null,null));
		request.setAttribute("subjectThreeResult", subjectThreeResult);
		request.setAttribute("department",department);
	    return"backHome/examManage/subjectThreeResult/updateSubjectThreeResult";
	}
	
	/**
	 * 修改科目三考试结果登记
	 * @param request
	 * @param subjectThreeResult
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/updateSubjectThreeResult")
	public String updateSubjectThreeResult(HttpServletRequest request,SubjectThreeResult subjectThreeResult)throws Exception{
		String [] stuid=request.getParameterValues("stuid");
		String [] stufseq=request.getParameterValues("stufseq");
		String [] stucfzkzmbh=request.getParameterValues("stucfzkzmbh");
		String [] stufnumber=request.getParameterValues("stufnumber");
		String [] stuname=request.getParameterValues("stuname");
		String [] stucfidcardno=request.getParameterValues("stucfidcardno");
		String [] stucfsex=request.getParameterValues("stucfsex");
		for (int i = 0; i < stucfsex.length; i++) {
			if(stucfsex[i].equals("男")){
				stucfsex[i]="1";
			}else{
				stucfsex[i]="2";
			}
		}
		String [] stucfsjhm=request.getParameterValues("stucfsjhm");
		String [] stucflxdh=request.getParameterValues("stucflxdh");
		String [] stucfslzjcxdh=request.getParameterValues("stucfslzjcxdh");
		String [] stucfclazzName=request.getParameterValues("stucfclazzName");
		String [] stucfamount=request.getParameterValues("stucfamount");
		String [] stucfreceived=request.getParameterValues("stucfreceived");
		String [] stucfarrearage=request.getParameterValues("stucfarrearage");
		String [] stucffavorable=request.getParameterValues("stucffavorable");
		String [] stucfvip=request.getParameterValues("stucfvip");
		String [] stucflocal=request.getParameterValues("stucflocal");
		for (int i = 0; i < stucflocal.length; i++) {
			if(stucflocal[i].equals("本地")){
				stucflocal[i]="1";
			}else if(stucflocal[i].equals("外地")){
				stucflocal[i]="2";
			}else{
				stucflocal[i]="3";
			}
		}
		String [] stucfexamresult=request.getParameterValues("stucfexamresult");
		String [] stucfremark=request.getParameterValues("stucfremark");
		//修改父类
		// 获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		// 获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
		// 把创建时间和业务日期清空不让修改
		subjectThreeResult.setFcreatetime(null);
		//subjectThreeResult.setFbizdate(null);
		subjectThreeResult.setFlastupdateuserid(user.getFid());
		subjectThreeResult.setFlastupdatetime(updateTime);
		//修改
		int row = subjectThreeResultService.updateSubjectThreeResult( user,subjectThreeResult, stuid, stufseq, stucfzkzmbh, stufnumber, stuname, stucfidcardno,
				stucfsex, stucfsjhm, stucflxdh, stucfslzjcxdh, stucfclazzName, stucfamount, stucfreceived, stucfarrearage, stucffavorable, 
				stucfvip, stucflocal, stucfexamresult, stucfremark);
		String result="";
		if(row >0){
			result="1";
		}
		// 添加日志
		customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目三考试结果登记进行修改", null, user.getFid());
	return "redirect:/DrivingSys/querySubjectThreeResult/look.action?type="+result;
	}
	
	/**
	 * 根据fid删除科目三考试信息
	 * @param request
	 * @param deleteId
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteSubjectThreeResultByFid")
	public String deleteSubjectOneRegByFid(HttpServletRequest request, String[] deleteId,String fid)throws Exception{
		User user = (User) request.getSession().getAttribute("user");
        //删除记录
		if(fid==null || fid.equals("")){
			for (int i = 0; i < deleteId.length; i++) {
	            /*过滤为空的删除操作*/
	            if (!deleteId[i].equals("")&& deleteId[i]!=null) {
	            	//根据fid查找单据编号
					SubjectThreeResult subjectThreeResult =subjectThreeResultService.selectSubjectThreeResultByFid(deleteId[i]);
					//删除历史流程或者进行中的流程
					activitiUtil.deleteTask(ActivitiKey.PUBLIC_KEY,subjectThreeResult.getFnumber());
	            	subjectThreeResultService.deleteSubjectThreeResult(deleteId[i]);//删除父类
	            	subjectThreeResultentryService.deleteSubjectThreeResultentryByParentid(deleteId[i],user,subjectThreeResult.getFbizdate(),(String)subjectThreeResult.getFnumber());//删除子类
	            }
	        }	
		}else{
			//根据fid查找单据编号
			SubjectThreeResult subjectThreeResult =subjectThreeResultService.selectSubjectThreeResultByFid(fid);
			//删除历史流程或者进行中的流程
			activitiUtil.deleteTask(ActivitiKey.PUBLIC_KEY,subjectThreeResult.getFnumber());
			subjectThreeResultService.deleteSubjectThreeResult(fid);//删除父类
        	subjectThreeResultentryService.deleteSubjectThreeResultentryByParentid(fid,user,subjectThreeResult.getFbizdate(),(String)subjectThreeResult.getFnumber());//删除子类
        }
		//添加日志
        customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目三考试结果登记进行删除", null, user.getFid());
		return "redirect:/DrivingSys/querySubjectThreeResult/look.action";
	}
	
	/**
	 * 根据考试日期和车型查找考试的学员
	 * @param cfcartype
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/selStudentsBySubscribedThree")
	public Object selStudentsBySubscribedOne(HttpServletRequest request,String examdate,String cfcartype,String name)throws Exception{
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    if("".equals(name)){
	    	name= null;
	    }
	    if(name !=null){
	    	name = name.trim();
	    }
	    if(examdate !=null){
	    	examdate=examdate.trim();
	    }
		//首先查找对应日期和车型已经登记过并审核的科目三考试登记的单据
		List<SubjectThreeReg> subjectThreeRegList=subjectThreeRegService.selSubjectThreeRegByfbizdate(user.getFcompanyid(),examdate, cfcartype);		
		List<SubjectThreeRegentry> subjectThreeRegentryList=new ArrayList<>();
		if(subjectThreeRegList.size() !=0){//如果不等于0
			for (SubjectThreeReg subjectThreeReg : subjectThreeRegList) {
				List<SubjectThreeRegentry> list=new ArrayList<>();			
				list=subjectThreeRegentryService.selSubjectThreeRegentryByParentId(subjectThreeReg.getFid(),name);
				for (SubjectThreeRegentry subjectThreeRegentry : list) {
					subjectThreeRegentryList.add(subjectThreeRegentry);
				}
			}				
		}
		//防止出现误操作出现重复数据，所以需要做去重操作
		for (int i = 0; i < subjectThreeRegentryList.size(); i++) {
			for (int j = subjectThreeRegentryList.size()-1; j >i ; j--) {
				if(subjectThreeRegentryList.get(i).getCfstudentid().equals(subjectThreeRegentryList.get(j).getCfstudentid())){
					subjectThreeRegentryList.remove(j);
				}
			}
		}
		return subjectThreeRegentryList;				
	}


	/**
	 * 提交科目三考试结果登记单据
	 * @param fid
	 * @param request
	 * @param fnumber
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "submitSubjectThreeResultActiviti")
	@ResponseBody
	public Object submitSubjectThreeResultActiviti(String fid, HttpServletRequest request, String fnumber)throws  Exception{
		//获取父类信息
		SubjectThreeResult _subjectThreeResult=subjectThreeResultService.selectSubjectThreeResultByFid(fid);
		//查找子类信息
		List<SubjectThreeResultentry> subjectThreeResultentries = subjectThreeResultentryService.selSubjectThreeResultentryByParentId(fid, null,null);
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		SubjectThreeResult subjectThreeResult =new SubjectThreeResult();
		subjectThreeResult.setFid(fid);
		subjectThreeResult.setCfbillstate(4L);
		subjectThreeResult.setFlastupdateuserid(user.getFid());
		//创建流程
		axamine.submissionProcess(fnumber);
		int row=subjectThreeResultService.submitSubjectThreeResult(subjectThreeResult);
		for (int i = 0; i <subjectThreeResultentries.size() ; i++) {
			customLogService.addLog("考试管理", "提交了学员:"+subjectThreeResultentries.get(i).getCfstudentno()+subjectThreeResultentries.get(i).getStudentName()
					+",科目三考试结果登记!申请车型:"+subjectThreeResultentries.get(i).getCfsqzjcx()+",考试日期:"+_subjectThreeResult.getFbizdate()+",单据编号:"+_subjectThreeResult.getFnumber(), subjectThreeResultentries.get(i).getCfstudentid(), user.getFid());
		}
		String result="failed";
		if(row >0){
			result="success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 审核单据
	 * @param request
	 * @param fid
	 * @param agree
	 * @param auditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "checkSubjectThreeResultActiviti")
	@ResponseBody
	public Object checkSubjectThreeResultActiviti(HttpServletRequest request,String fnumber,String fid,String agree,String auditcomment)throws  Exception{
		//获取父类信息
		SubjectThreeResult _subjectThreeResult=subjectThreeResultService.selectSubjectThreeResultByFid(fid);
		//查找子类信息
		List<SubjectThreeResultentry> subjectThreeResultentries = subjectThreeResultentryService.selSubjectThreeResultentryByParentId(fid, null,null);
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		SubjectThreeResult subjectThreeResult =new SubjectThreeResult();
		//获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
		String result ="failed";
		int row1=0;
		if(agree.equals("1")){//同意
			ServerResponse serverResponse = axamine.auditProcess(fnumber, agree, auditcomment);
			if(serverResponse.getStatus() == 1){//结束
				subjectThreeResult.setFid(fid);
				subjectThreeResult.setCfbillstate(5L);
				subjectThreeResult.setFlastupdateuserid(user.getFid());
				subjectThreeResult.setFauditorid(user.getFid());
				row1 = subjectThreeResultService.updateSubjectThreeResult(subjectThreeResult);
				if(row1 >0 ){//修改单据和修改学员都成功
					result = "success";
				}
			}else if(serverResponse.getStatus() == 2){
				result = "success";
			}else{

			}
			for (int i = 0; i <subjectThreeResultentries.size() ; i++) {
				customLogService.addLog("考试管理", "审核了学员:"+subjectThreeResultentries.get(i).getCfstudentno()+subjectThreeResultentries.get(i).getStudentName()
						+",科目三考试结果登记!申请车型:"+subjectThreeResultentries.get(i).getCfsqzjcx()+",考试日期:"+_subjectThreeResult.getFbizdate()+",单据编号:"+_subjectThreeResult.getFnumber(), subjectThreeResultentries.get(i).getCfstudentid(), user.getFid());
			}
		}else{
			ServerResponse serverResponse = axamine.auditProcess(fnumber, agree, auditcomment);
			if(serverResponse.getStatus() == 2){
				subjectThreeResult.setFid(fid);
				subjectThreeResult.setCfbillstate(3L);
				subjectThreeResult.setFlastupdateuserid(user.getFid());
				subjectThreeResult.setFauditorid(user.getFid());
				//修改父类
				row1 =subjectThreeResultService.submitSubjectThreeResult(subjectThreeResult);
				if(row1 >0){
					result = "success";
				}
			}
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 反审核科目三考试结果单据
	 * @param request
	 * @param fid
	 * @param againstAuditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "againstCheckSubjectThreeResultActiviti")
	@ResponseBody
	public Object againstCheckSubjectThreeResultActiviti(HttpServletRequest request,String fid,String fnumber,String againstAuditcomment )throws  Exception{
		//获取当前登录用户的信息
		User user =(User)request.getSession().getAttribute("user");
		//获取父类信息
		SubjectThreeResult _subjectThreeResult=subjectThreeResultService.selectSubjectThreeResultByFid(fid);
		//查找子类信息
		List<SubjectThreeResultentry> subjectThreeResultentries = subjectThreeResultentryService.selSubjectThreeResultentryByParentId(fid, null,null);
		String result ="falied";
		//将单据状态修改成保存状态3
		SubjectThreeResult subjectThreeResult = new SubjectThreeResult();
		subjectThreeResult.setFid(fid);
		subjectThreeResult.setCfbillstate(3L);//保存状态
		subjectThreeResult.setFauditorid(user.getFid());//设置反审计人id
		int row = subjectThreeResultService.submitSubjectThreeResult(subjectThreeResult);
		axamine.againstAuditProcess(fnumber,againstAuditcomment);
		for (int i = 0; i <subjectThreeResultentries.size() ; i++) {
			customLogService.addLog("考试管理", "反审核了学员:"+subjectThreeResultentries.get(i).getCfstudentno()+subjectThreeResultentries.get(i).getStudentName()
					+",科目三考试结果登记!申请车型:"+subjectThreeResultentries.get(i).getCfsqzjcx()+",考试日期:"+_subjectThreeResult.getFbizdate()+",单据编号:"+_subjectThreeResult.getFnumber(), subjectThreeResultentries.get(i).getCfstudentid(), user.getFid());
		}
		if (row > 0) {
			result = "success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}


	/*自制迭代器删除*/
	@SuppressWarnings("unchecked")
	public void iteratorRemove(List<SubjectThreeResult> list, SubjectThreeResult obj){

		Iterator<SubjectThreeResult> it = list.iterator();
		while(it.hasNext()){

			SubjectThreeResult item = it.next();

			if (item.equals(obj))
			{
				it.remove();//remove the current item
			}

		}
	}

	@SuppressWarnings("unchecked")
    /**
     * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
     * @return 返回PageBean实体类
     * @throws Exception
     */
    public PageBean<SubjectThreeResult> getPageBean(HttpServletRequest request, String companyId, String fnumber,
            String fdescription,String studentName,String beginTime, String endTime,String cfexamresult) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
		psql.append(" SELECT distinct S.FCREATORID,S.FCREATETIME,S.FLASTUPDATEUSERID,S.FLASTUPDATETIME,S.FCONTROLUNITID,S.FNUMBER,"
				+ "S.FHANDLERID,to_char(S.FBIZDATE,'YYYY-MM-DD') FBIZDATE ,S.FDESCRIPTION,S.FHASEFFECTED,S.FAUDITORID,S.FSOURCEBILLID,S.FSOURCEFUNCTION, "
				+" S.FID,S.FFIVOUCHERED,S.CFFICOMPANYID,S.CFBILLSTATE,"
				+ "S.CFCARTYPE, E.NAME AS checkName,U.NAME AS createName "
				+ "FROM CT_DS_SUBJECTTHREERESULT S LEFT JOIN T_E_USER U ON U.FID=S.FCREATORID LEFT JOIN T_E_USER E ON E.FID=S.FAUDITORID "
				+" LEFT JOIN CT_DS_SUBJECTTHREERESULTENTRY S1 ON S1.FPARENTID = S.FID "
				+" LEFT JOIN CT_DS_STUDENT STU ON STU.FID = S1.CFSTUDENTID "
				+ "WHERE S.FCONTROLUNITID='" + companyId + "'");
		if (fnumber == null || fnumber.equals("")) {

		} else {
			psql.append("AND S.FNUMBER LIKE '%" + fnumber + "%' ");
		}
		if (fdescription == null || fdescription.equals("")) {

		} else {
			psql.append("AND S.FDESCRIPTION LIKE '%" + fdescription + "%'");
		}
		if (studentName == null || studentName.equals("")) {

		} else {
			psql.append("AND STU.FNAME_L2 LIKE '%" + studentName + "%'");
		}
		if (beginTime == null || endTime == null) {
		/*	beginTime = TimeFormat.getMonth();
		} else if (endTime == null || endTime.equals("")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			endTime = sdf.format(new Date());
			psql.append("AND TO_CHAR(S.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'");*/
		} else {
			psql.append("AND TO_CHAR(S.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'");
		}
		if (cfexamresult==null||"".equals(cfexamresult)){

		}else{
			psql.append("AND s1.CFEXAMRESULT = '"+cfexamresult+"'");

		}
		/*psql.append(" ORDER BY to_char(S.FBIZDATE,'YYYY-MM-DD') DESC");*/
		psql.append(" ORDER BY FBIZDATE DESC");
        int psize = 50; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = subjectThreeResultService.selectPage(pindex, psql.toString(), psize);
        PageBean<SubjectThreeResult> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<SubjectThreeResult>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }
	
	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=subjectThreeResultService.selectPageCount(psql);
		return paramMap;
	}

	/**
	 * 查找科目三考试结果登记 导出Excel
	 * @param response
	 * @param request
	 * @param fnumber
	 * @param fdescription
	 * @param studentName
	 * @param beginTime
	 * @param endTime
	 */
	@RequestMapping(value = "/importSubjectThreeResult")
	public void importSubjectThreeResult(HttpServletResponse response, HttpServletRequest request
			, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
			, @RequestParam(value = "fdescription", defaultValue = "") String fdescription
			, @RequestParam(value = "studentName", defaultValue = "") String studentName
			, @RequestParam(value = "beginTime", defaultValue = "") String beginTime
			, @RequestParam(value = "endTime", defaultValue = "") String endTime
			, @RequestParam(value = "cfexmaresult", defaultValue = "") String cfexmaresult){
		if("".equals(studentName)){
			studentName =null;
		}
		if ("".equals(cfexmaresult)){
			cfexmaresult=null;
		}
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//定义接收类型
		List<Object> data = new ArrayList<>();
		//查询数据
		List<SubjectThreeResult> subjectThreeResults=subjectThreeResultService.selectSubjectThreeResult(user.getFcompanyid(),fnumber,fdescription,beginTime,endTime);
		for (SubjectThreeResult subjectThreeResult :subjectThreeResults){
			subjectThreeResult.setSubjectThreeResultentryList(subjectThreeResultentryService.selSubjectThreeResultentryByParentId(subjectThreeResult.getFid(),studentName,cfexmaresult));
			for (int i = 0; i <subjectThreeResult.getSubjectThreeResultentryList().size() ; i++) {
				data.add(subjectThreeResult.getFnumber());
				data.add(subjectThreeResult.getFbizdate());
				data.add(subjectThreeResult.getFdescription());
				data.add(subjectThreeResult.getCheckName());
				data.add(subjectThreeResult.getCreateName());
				if(subjectThreeResult.getCfbillstate() == 3L){
					data.add("保存");
				}else if(subjectThreeResult.getCfbillstate() == 4L){
					data.add("提交");
				}else{
					data.add("审核");
				}
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getStudentName());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfstudentno());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfzkzmbh());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfidcardno());
				if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfsex() == 1L){
					data.add("男");
				}else if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfsex() == 2L){
					data.add("女");
				}else{
					data.add("");
				}
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfmobile());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfphone());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfsqzjcx());
				if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfbdyd() == 1L){
					data.add("本地");
				}else if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfbdyd() == 2L){
					data.add("异地");
				}else if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfbdyd() == 3L){
					data.add("学生");
				}else{
					data.add("");
				}
				if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfexamresult() == 1L){
					data.add("合格");
				}else if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfexamresult() == 2L){
					data.add("不合格");
				}else if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfexamresult() == 3L){
					data.add("缺考");
				}
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfremark());
				if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfvip() !=null){
					if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfvip() == 0L){
						data.add("是");
					}else if(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfvip() == 1L){
						data.add("否");
					}
				} else{
					data.add(null);
				}
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfclazz());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfsqzjcx());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfreceivable());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfreceived());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCfarrearage());
				data.add(subjectThreeResult.getSubjectThreeResultentryList().get(i).getCffavorable());
			}
		}
		//头部数据
		String head[] = {"单据编号", "业务日期", "参考信息", "审核人名称", "制单人名称","单据状态", "学员姓名","学员编码","准考证名编号","身份证号码",
				"性别","手机号码","电话","申请车型","本地/异地","考试结果","备注","vip","班级","车型",
				"应收", "已收","欠费","优惠"};
		//长度
		Integer length[] = {9000, 5000, 5000, 3000, 3000, 3000, 3000, 9000, 5000, 9000,
				3000, 5000, 3000, 3000, 3000, 3000, 3000, 3000, 5000, 3000,
				3000, 3000, 3000, 3000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "科目三考试结果登记" + TimeFormat.getNowTime2() + ".xls", "科目三考试结果登记", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
